package com.mzbopen.rightbottommoreview;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.lang.ref.WeakReference;

public class ScreenUtil {
    private DisplayMetrics dm;
    private static ScreenUtil instance;
    private WeakReference<Activity> reference;

    public Activity getBaseActivity() {
        return reference.get();
    }

    public static synchronized ScreenUtil getInstance(Activity activity) {
        if (instance == null) {
            instance = new ScreenUtil(activity);
        }
        return instance;
    }

    public static DisplayMetrics getDensity(Context context) {
        return context.getApplicationContext().getResources().getDisplayMetrics();
    }

    private ScreenUtil(Activity activity) {
        dm = new DisplayMetrics();
        reference = new WeakReference<>(activity);
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    }

    public int getStatusHigh() {
        Rect outRect = new Rect();
        getBaseActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
        return dm.heightPixels - outRect.height();
    }

    public DisplayMetrics getDm() {
        return dm;
    }

    public void setLayoutParam(View view, int width, int height) {
        if (view != null && view.getLayoutParams() != null) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            if (layoutParams == null) layoutParams = new ViewGroup.LayoutParams(width, height);
            else {
                if (width > 0) layoutParams.width = width;
                if (height > 0) layoutParams.height = height;
            }
            view.setLayoutParams(layoutParams);
        }
    }

    public void setMarginParam(View view, int left, int right, int top, int bottom) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof LinearLayout.LayoutParams) {
            LinearLayout.LayoutParams linParams = (LinearLayout.LayoutParams) view.getLayoutParams();
            if (left > 0) linParams.leftMargin = left;
            if (right > 0) linParams.rightMargin = right;
            if (top > 0) linParams.topMargin = top;
            if (bottom > 0) linParams.bottomMargin = bottom;
        } else if (layoutParams instanceof RelativeLayout.LayoutParams) {
            RelativeLayout.LayoutParams relParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            if (left > 0) relParams.leftMargin = left;
            if (right > 0) relParams.rightMargin = right;
            if (top > 0) relParams.topMargin = top;
            if (bottom > 0) relParams.bottomMargin = bottom;
        } else if (layoutParams instanceof FrameLayout.LayoutParams) {
            FrameLayout.LayoutParams relParams = (FrameLayout.LayoutParams) view.getLayoutParams();
            if (left > 0) relParams.leftMargin = left;
            if (right > 0) relParams.rightMargin = right;
            if (top > 0) relParams.topMargin = top;
            if (bottom > 0) relParams.bottomMargin = bottom;
        }

        view.setLayoutParams(layoutParams);
    }


    /**
     * @param context
     * @return
     * @description 获取屏幕宽度
     */
    public static final int getScreenWidth(Context context) {
        DisplayMetrics var2 = new DisplayMetrics();
        if (context!=null&&context.getSystemService(Context.WINDOW_SERVICE)!=null){
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (wm != null) {
                wm.getDefaultDisplay().getMetrics(var2);
            }
        }
        return var2.widthPixels;
    }

    /**
     * @param context
     * @return
     * @description 获取屏幕高度
     */
    public static final int getScreenHeight(Context context) {
        DisplayMetrics var2 = new DisplayMetrics();
        if (context!=null&&context.getSystemService(Context.WINDOW_SERVICE)!=null){
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (wm != null) {
                wm.getDefaultDisplay().getMetrics(var2);
            }
        }

        return var2.heightPixels;
    }

    public static final int dp2px(Context context, float dpValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        } catch (Exception e) {
            return (int) dpValue;
        }
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dp(Context context, float pxValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (pxValue / scale + 0.5f);
        } catch (Exception e) {
            return (int) pxValue;
        }
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int dip2px(float dipValue, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);

    }

    //    获取状态栏高度
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    //     获取导航栏高度
    public static int getDaoHangHeight(Context context) {
        int result = 0;
        int resourceId = 0;
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid != 0) {
            resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
//            CMLog.show("高度："+resourceId);
//            CMLog.show("高度："+context.getResources().getDimensionPixelSize(resourceId) +"");
            return context.getResources().getDimensionPixelSize(resourceId);
        } else
            return 0;
    }

    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        if (activity==null)return;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }

    public static String getSmallBegin(int nub) {
        String small = "";
        for (int i = 0; i < nub; i++)
            small += "<small>";
        return small;
    }

    public static String getSmallEnd(int nub) {
        String small = "";
        for (int i = 0; i < nub; i++)
            small += "</small>";
        return small;
    }


//    /**
//     * 判断当前view是否在屏幕可见
//     */
//    public static boolean getLocalVisibleRect(Activity activity, View view) {
//        int screenWidth = ScreenUtil.getScreenWidth(activity);
//        int screenHeight = ScreenUtil.getScreenHeight(activity);
//        Rect rect = new Rect(0, 0, screenWidth, screenHeight);//得到屏幕矩阵
//        return  view.getGlobalVisibleRect(rect);
//    }

    /**
     * 判断当前view是否在屏幕可见
     */
    public static boolean getLocalVisibleRect(Activity activity, View view) {
        int screenWidth = ScreenUtil.getScreenWidth(activity);
        int screenHeight = ScreenUtil.getScreenHeight(activity);
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);//得到屏幕矩阵
        view.getGlobalVisibleRect(rect);
        return rect.top!=0;
    }
    public static boolean getLocalVisibleRectLog(Activity activity, View view) {
        int screenWidth = ScreenUtil.getScreenWidth(activity);
        int screenHeight = ScreenUtil.getScreenHeight(activity);
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);//得到屏幕矩阵
        view.getGlobalVisibleRect(rect);
        return rect.top!=0;
    }

//    /**
//     * 判断当前view是否在屏幕可见
//     */
//    public static boolean getLocalVisibleRect(Activity activity, View view) {
//        int screenWidth = ScreenUtil.getScreenWidth(activity);
//        int screenHeight = ScreenUtil.getScreenHeight(activity);
//        Rect rect = new Rect(0, 0, screenWidth, screenHeight);//得到屏幕矩阵
//        int[] location = new int[2];
//        view.getLocationInWindow(location);
//        boolean isShow = view.getLocalVisibleRect(rect);
//        Log.i("1231241241","rect.top="+rect.top);
//        Log.i("1231241241","isShow="+isShow);
//        return isShow;
//    }

    /**
     * 获取底部虚拟导航栏的高度
     * @return
     */
    public static int getNavigationBarHeight(Activity activity) {
        int height = 0;
        //屏幕实际尺寸
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(dm);
        int phoneHeight = dm.heightPixels;
        if (isNavigationBarExist(activity)) {
            Resources resources = activity.getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height",
                    "dimen", "android");
            if (resourceId > 0) {
                //获取NavigationBar的高度
                height = resources.getDimensionPixelSize(resourceId);
            }
        }
        if (height > 0){
            //处理全屏模式下，部分手机isNavigationBarExist()始终返回true，NavigationBar的高度
            int diffValue = (getScreenHeight(activity) + getStatusBarHeight(activity) + height) - phoneHeight;
            if (diffValue > 0){
                height -= diffValue;
            }
        }
        return height;
    }
    public static boolean isNavigationBarExist(Activity activity){
        ViewGroup vp = (ViewGroup) activity.getWindow().getDecorView();
        if (vp != null) {
            for (int i = 0; i < vp.getChildCount(); i++) {
                vp.getChildAt(i).getContext().getPackageName();
                if (vp.getChildAt(i).getId() != View.NO_ID
                        && "navigationBarBackground".equals(activity.getResources().getResourceEntryName(vp.getChildAt(i).getId()))) {
                    return true;
                }
            }
        }
        return false;
    }
}
